package com.jingdianjichi.practice.server.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.jingdianjichi.practice.server.intercepter.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

/**
 * 实现对MVC的处理,全局处理
 */
@Configuration
public class GlobalConfig extends WebMvcConfigurationSupport {

    //因为我们的返回是基于jackson做的,如果=返回的泛型是空的就会报错的,序列化的时候如果是空的就会报错的
    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);

        converters.add(mappingJackson2HttpMessageConverter());
    }


    //因为我们的数据返回MVC底层都是基于JackSon做的,人家在序列化的时候,如果遇到null的时候,就会报错的
    private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(){
        ObjectMapper objectMapper = new ObjectMapper();

        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);     //这个配置就是如果是空的对象的话,也是可以进行返回的

        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);           //这里就是如果是null的话,我们就影藏掉了,你也可以去实体类中,一个一个加注解这时全局的,null的信息我们隐藏掉

        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(objectMapper);

        return converter;
    }

    //做Mvc的统一拦截器,否则每个方法都要写的亲,解析请求头亲
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**");    //拦截所有的请求走我们的拦截器
    }


}
